﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Mammoth.Entities;
using Mammoth.Events;
using Mammoth.Services;

namespace Mammoth.ViewModels
{
    public partial class MainWindowViewModel
    {
        private void InitializeDatabase()
        {
            GTalkService.Message += GTalk_Message_Sync;
            GTalkService.FriendListLoad += GTalk_FriendListLoad_Sync;
            GTalkService.AccountListChange += GTalk_AccountListChange_Sync;

            Task.Factory.StartNew(() => SyncAccounts());
        }

        private void GTalk_FriendListLoad_Sync(object sender, ServiceEventArgs e)
        {
            Task.Factory.StartNew(() => SyncUsers());
        }

        private void GTalk_AccountListChange_Sync(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => SyncAccounts());
        }

        private void GTalk_Message_Sync(object sender, ServiceMessageEventArgs e)
        {
            Task.Factory.StartNew(() => SaveMessage(e.ServiceEmail, e.BuddyEmail, e.Message));
        }

        private void SaveMessage(string serviceEmail, string buddyEmail, string message)
        {
            using (var r = repositoryFactory.GetRepository<InboxEntity>())
            using (var a = repositoryFactory.GetRepository<AccountEntity>())
            using (var b = repositoryFactory.GetRepository<BuddyEntity>())
            {
                try
                {
                    var acc = a.Get(x => x.Email == serviceEmail).FirstOrDefault();
                    var buddy = b.Get(x => x.Email == buddyEmail).FirstOrDefault();
                    var en = new InboxEntity()
                    {
                        Buddy = buddy,
                        Service = acc,
                        Message = message
                    };
                    r.Save(en);
                    Dispatcher.RaiseMessageDataChangeEvent();
                }
                catch (Exception)
                {
                    Dispatcher.RaiseErrorEvent("Terjadi kesalahan saat menyimpan data");
                }
            }
        }

        private void SyncAccounts()
        {
            foreach (var item in GTalkService.AccountList)
            {
                Synchronize<AccountEntity>(item);
            }
        }

        private void SyncUsers()
        {
            foreach (var item in GTalkService.BuddyList)
            {
                Synchronize<BuddyEntity>(item);
            }
        }

        void Synchronize<T>(T entity) where T : Entity, IGTalkAccountEntity
        {
            using (var r = repositoryFactory.GetRepository<T>())
            {
                try
                {
                    var q = r.Get(x => x.Email == entity.Email).FirstOrDefault();
                    if (q == null)
                        r.Save(entity);
                    else
                    {
                        entity.Id = q.Id;
                        r.Save(entity);
                    }
                }
                catch (Exception)
                {
                    Dispatcher.RaiseErrorEvent("Terjadi kesalahan saat menyimpan data");
                }
            }
        }

    }
}
